var pcommentStatus = {
    lastComment: "",
    repliedId: 0,
    connectJsLoaded: false
};
function templateFormat(format) {
	if (!templateFormat._formatRE) {
		templateFormat._formatRE = /(\{[^\}\{]+\})/g;
	}
	var values = arguments;
	return format.replace(templateFormat._formatRE, function (str, m) {
		var index = parseInt(m.substr(1));
		var value = values[index + 1];
		if (!value) {return "";}
		return value.toString();
	});
}
function smtCmtIndicating() {
    var comment = $("pcomment");
    var submitBtn = $("submitComment");
    if (comment) {comment.disabled="disabled";}
    if (submitBtn) {submitBtn.style.backgroundColor="#808080";submitBtn.disabled="disabled";}
}
function clrSmtCmtPrompt() {
    var comment = $("pcomment");
    var submitBtn = $("submitComment");
    if (comment) {comment.disabled="";}
    if (submitBtn) {submitBtn.style.backgroundColor="#005EAC";submitBtn.disabled="";}
}
function errAlert(prompt) {
    alert(prompt);
}
function smtCmtErrPrompt(prompt) {
    errAlert(prompt);
    clrSmtCmtPrompt();
}
function InsertNewCmt(respJson) {
    if (!InsertNewCmt._cmtTemplate) {
        InsertNewCmt._cmtTemplate = "<a class=\"float_left\" href=\"/profile?id={0}\"><img class=\"comment_photo\" src=\"{1}\"/></a>" +
            "<div class=\"comment_info\">" + 
            "<span class=\"float_right\"><a class=\"x_mark\" href=\"javascript:delComment({2});\">x</a></span>" +
            "<a href=\"/profile?id={0}\">{3}</a> " +
            "<span class=\"comment_time\">{4}</span>" +
            "</div>" + 
            "<div class=\"comment_reply\">" +
            "{5}" +
            "</div>";
    }
    var cmtList = $("comments");
    if (cmtList) {
        var cmtBlock = document.createElement("div");
        cmtBlock.className = "comment_block";
        cmtBlock.id = "c" + respJson.cid.toString();
        var cmtEditorBlock = $("ceditor_blk");
        cmtList.insertBefore(cmtBlock, cmtEditorBlock);
        cmtBlock.innerHTML = templateFormat(InsertNewCmt._cmtTemplate, respJson.commenterId, respJson.commenterPhoto, respJson.cid, respJson.commenterName, respJson.time, respJson.pcomment);
    }
}
function submitComment(pid, authorId, userName, title, paperLink, siteName, siteUrl) {
    var comment = $("pcomment");
    if (comment) {
        var commentValue = comment.value;
        if (!commentValue) {
            smtCmtErrPrompt("评论内容不能为空:)");
            return false;
        }
        smtCmtIndicating();
        var url = "/pcomment";
        var callback = function(respJson) {
            if (respJson) {
                if (!respJson.errCode) {
                    InsertNewCmt(respJson);
                    clrSmtCmtPrompt();
                    var comment = $("pcomment");
                    if (comment) {comment.value = "";}
                    sendXnNotifications(authorId, commentValue, userName, title, paperLink, siteName, siteUrl);
                }
                else {smtCmtErrPrompt("出错了：" + respJson.errMsg);}
            }
            else {smtCmtErrPrompt("出错了：未知错误");}
        };
        var options = {
            values: {op:"new",pcomment:commentValue,pid:pid},
            errorHandler: function(status, statusText) {smtCmtErrPrompt("出错了：" + statusText);},
            timeout: 3000,
            timeoutHandler: function() {smtCmtErrPrompt("出错了：连接服务器超时！");}
        };
        HTTP.post(url, callback, options);
    }
}
function delCmtDomBlk(cid) {
    var cmtList = $("comments");
    var cmtBlock = $("c" + cid.toString());
    if (cmtList && cmtBlock) {cmtList.removeChild(cmtBlock);}
}
function delComment(cid) {
    if (!confirm("你真的想删除这条评论吗？")) {return;}
    if (cid) {
        var url = "/pcomment";
        var callback = function(respJson) {
            if (respJson) {
                if (!respJson.errCode) {
                    delCmtDomBlk(cid);
                }
                else {errAlert("出错了：" + respJson.errMsg);}
            }
            else {errAlert("出错了：未知错误");}
        };
        var options = {
            values: {op:"del",cid:cid},
            errorHandler: function(status, statusText) {errAlert("出错了：" + statusText);},
            timeout: 3000,
            timeoutHandler: function() {errAlert("出错了：连接服务器超时！");}
        };
        HTTP.post(url, callback, options);
    }
}
function replyToCommenter(xnuid, commenterId, commenterName) {
    if (!xnuid) {errAlert("你需要先登录才能回复:)"); return}
    var comment = $("pcomment");
    if (comment && (comment.value == "" || pcommentStatus.lastComment != comment.value)) {
        comment.value = "回复" + commenterName + "：" + comment.value
        pcommentStatus.lastComment = comment.value;
        pcommentStatus.repliedId = commenterId;
    }
}
function clrRepliedId() {
    pcommentStatus.repliedId = 0;
}

function sendXnNotifications(authorId, commentValue, userName, title, paperLink, siteName, siteUrl) {
    notifCebox = $("notification");
    if (notifCebox.checked && pcommentStatus.connectJsLoaded) {
        repliedIds = [authorId];
        if (commentValue.indexOf("回复") == 0 && pcommentStatus.repliedId && pcommentStatus.repliedId != authorId) {
            repliedIds[repliedIds.length] = pcommentStatus.repliedId;
        }
        XN.Main.get_sessionState().waitUntilReady(function(){
            var content = userName + "在<a href=\"" + siteUrl + "\">" + siteName + "</a>上的文章<a href=\"" + paperLink + "\">" + title + "</a>中回复了你！";
            XN.Main.apiClient.notifications_send(repliedIds, content, function(result, ex){});
        });
    }
    clrRepliedId();
}
function sendXnFeed(siteUrl, siteName, paperTitle, paperLink, paperSummary, imgSrc) {
    templateData = {
        "site":"<a href=\"" + siteUrl + "/\">" + siteName + "</a>",
        "content":"<a href=\"" + paperLink + "\">" + paperTitle + "</a>"
    };
    if (imgSrc) {
        templateData["images"] = [{"src":imgSrc, "href":paperLink}];
    }
    feedSettings = {
        "template_bundle_id": 1,
        "template_data": templateData,
        "body_general": paperSummary,
        "callback": function(ok){},
        "user_message_prompt": "你觉得这篇文章如何？",
        "user_message": "文章简直太精彩了！"
    };
    XN.Connect.showFeedDialog(feedSettings);
}